<script setup>
import { ref } from "vue";

// Api
import { list, get } from "@/api/fs";

// Components
import Taro from "@tarojs/taro";

// Config
import { tokenKey } from "@/config/cache-keys";
import { cdnUrl } from "@/config/environment";
// Hooks
import { getCookie } from "@/hooks/useCookie";
import { onLink } from "@/hooks/useRoute";
import useDownload from "@/hooks/useDownload";
import useClipboard from "@/hooks/useClipboard";
import { useLoad, useDidHide, useDidShow } from "@tarojs/taro";

// Utils
import { isEmpty } from "lodash";

const form = ref({ path: "", password: "", page: 1, per_page: 0, refresh: false });
const listPath = ref([]);
const stacks = ref([]);
const mediaList = ref([]);
const tokenFlag = isEmpty(getCookie(tokenKey));
const message = ref("");
const hideFlag = ref(false);

useLoad((options) => {
  stacks.value = options.stacks ? options.stacks.split(",") : [];
  form.value.path = stacks.value.join("");

  Taro.setNavigationBarTitle({
    title: `主页${form.value.path}`,
  });

  getList();
});

useDidShow(() => {
  hideFlag.value = false;
});

useDidHide(() => {
  if (hideFlag.value) {
    return;
  }

  stacks.value.pop();
});

async function getList() {
  Taro.showNavigationBarLoading();

  try {
    const {
      data: { content },
    } = await list(form.value);

    listPath.value = content || [];
  } catch (error) {
    message.value = error.message;
  }

  Taro.hideNavigationBarLoading();
}

async function onChange({ name, is_dir }) {
  if (is_dir) {
    stacks.value.push(`/${name}`);
    onLink(`/pages/index/index?stacks=${stacks.value.join(",")}`);
    return;
  }

  hideFlag.value = true;

  Taro.showLoading();

  const { data } = await get({ path: `${form.value.path}/${name}` });

  const pdfReg = /\.pdf$/i.test(name);

  if (pdfReg) {
    useDownload(data.raw_url);
    return;
  }

  const imageReg = /\.(gif|png|jpg|jpeg|webp|svg|psd|bmp|tif)$/i.test(name);
  const videoReg = /\.(swf|avi|flv|mpg|rm|mov|wav|asf|3gp|mkv|rmvb|mp4|mp3|ape|wma|m4a)$/i.test(name);

  if (videoReg || imageReg) {
    const type = imageReg ? "image" : "video";

    let current = mediaList.value.findIndex((item) => item.name === data.name);

    if (current === -1) {
      mediaList.value.unshift({ url: data.raw_url, type, name: data.name });
    }

    Taro.previewMedia({
      sources: mediaList.value,
      current,
    });

    Taro.hideLoading();
    return;
  }

  hideFlag.value = false;
  useClipboard(data.raw_url);
}

function onShowImage({ thumb, is_dir }) {
  if (is_dir) {
    return `${cdnUrl}/alist/icons/file.png`;
  }

  if (thumb) {
    return thumb;
  }

  return `${cdnUrl}/alist/icons/unknown.png`;
}

function onLogin() {
  onLink({ url: "/pages/login/index", linkType: "redirectTo" });
}
</script>

<template>
  <view class="index">
    <view class="index-content" v-if="listPath.length">
      <view class="index-content--container" v-for="item in listPath" :key="item.name" @click="onChange(item)">
        <image class="index-content--container__image" mode="heightFix" lazy-load :src="onShowImage(item)" />

        <view class="index-content--container__label">{{ item.name }}</view>
      </view>
    </view>

    <view class="index-message" v-if="message">
      {{ message }}
    </view>

    <view class="index-login" v-if="tokenFlag" @click="onLogin">登录</view>
  </view>
</template>

<style lang="scss">
.index-content {
  display: flex;
  flex-wrap: wrap;
  background: #f8f8f8;
  margin: 20px;
  font-size: 30px;
  padding: 30px 0px;
  padding-bottom: 0;
  border-radius: 10px;
  overflow: hidden;

  &--container {
    margin-bottom: 30px;
    width: 33.33%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    overflow: hidden;

    &__image {
      height: 100px;
      width: 100px;
    }

    &__label {
      width: 80%;
      text-align: center;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
  }
}

.index-login {
  position: fixed;
  bottom: 60px;
  left: 50%;
  transform: translateX(-50%);
  background: #06a8f5;
  padding: 10px 30px;
  color: #fff;
  font-weight: 700;
}

.index-message {
  margin: 20px;
  padding: 20px;
  border-radius: 10px;
  font-size: 40px;
  background: #f8f8f8;
}
</style>
